package com.mlethe.android.demo.banner.adapter;

import android.os.Bundle;
import android.util.SparseArray;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentPagerAdapter;
import androidx.viewpager.widget.PagerAdapter;

import com.mlethe.android.demo.banner.TestFragment;

public class ViewPagerAdapter extends FragmentPagerAdapter {

    private String[] mTitles;
    private SparseArray<Fragment> fragments = new SparseArray<>();

    public ViewPagerAdapter(FragmentManager fm, String[] titles) {
        super(fm, FragmentPagerAdapter.BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT);
        this.mTitles = titles;
    }

    @Override
    public int getCount() {
        return mTitles.length;
    }

    @Override
    public CharSequence getPageTitle(int position) {
        return mTitles[position];
    }

    @Override
    public Fragment getItem(int position) {
        Fragment fragment = fragments.get(position);//从集合中取出Fragment
        if (fragment == null){
            fragment = new TestFragment();
            int type = position;
            Bundle bundle = new Bundle();
            bundle.putInt("type", type);//这里的values就是我们要传的值
            fragment.setArguments(bundle);
            fragments.put(position, fragment);//存入集合中
        }
        return fragment;
    }

    @Override
    public void destroyItem(ViewGroup container, int position, Object object) {
    }

    @Override
    public int getItemPosition(@NonNull Object object) {
        return PagerAdapter.POSITION_NONE;
    }
}
